#include "database.h"
#include "database_thread.h"
#include <stdarg.h>

namespace engine
{
	bool Database::execute(const char *fmt, ...)
	{
		QUERY_BODY(fmt, buf)
		return push(new SqlStatement(buf));
	}

	bool Database::push(SqlOperation* op)
	{
		DatabaseThread* th = getMinLoadThread();

		return th->push(op);
	}

	DatabaseThread* Database::getMinLoadThread()
	{
		uint32 minLoad = 0xFFFFFFFF;
		size_t index = 0;
		for (size_t i = 0; i < mThreads.size(); ++i)
		{
			uint32 load = mThreads[i]->getQueueSize();
			if (load < minLoad)
			{
				minLoad = load;
				index = i;
			}
		}

		return mThreads[index];
	}

	void Database::handleResults()
	{
		for (size_t i = 0; i < mThreads.size(); ++i)
		{
			mThreads[i]->handleResults();
		}
	}

	void Database::printStat()
	{
		DatabaseThread* th = getMinLoadThread();

		uint32 size = th->getQueueSize();

		if (size > 100)
		{
			printf("Database queue size %d\n", size);
		}
	}
}